package com.emar.spring.controller;

import java.util.List;

import javax.servlet.ServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.emar.spring.common.Constant;
import com.emar.spring.model.UserEntity;
import com.emar.spring.service.UserService;

/**
 * 用户表操作类 
 */
@Controller
@RequestMapping(value="/user")
@SessionAttributes("currentUser")	//保存用户登录状态到session
public class UserController {
	private Log log = LogFactory.getLog(UserController.class);
	
	@Autowired
	private UserService userService;
	
	@RequestMapping(value="")
	public String user(Model model,ServletRequest request){
		return "login";
	}
	
	/**
	 * 用户登录判断
	 * @param username
	 * @param password
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(@RequestParam() String username,
			@RequestParam() String password,Model model){
		String url = "login";
		model.addAttribute( "username", username);
		model.addAttribute( "password", password);
		
		UserEntity user = userService.login(username, password);
		if(user!=null){		//用户存在
			if(password.equals(user.getPassword())){
				model.addAttribute( "currentUser", user);	//登录成功，用户信息存入session
				if(Constant.USER_STATUS_VALID.equals(user.getStatus())){			//判断用户状态，用户状态：0，待审核。1，审核通过。2，冻结。-1，删除
					
					if(Constant.USER_ROLE_ADMIN.equals(user.getRole())){			//判断是否是管理员登录
						log.info( "admin login success :"+user.getAccount());
						url = "admin/admin";
					}else{
						log.info( "user login success :"+user.getAccount());
						url = "main";
					}
				}else if(Constant.USER_STATUS_PREPARE.equals(user.getStatus())){			//用户状态为待审核
					model.addAttribute( "error",  "用户状态为待审核"); 
				}else if(Constant.USER_STATUS_FROZEN.equals(user.getStatus())){			//用户状态为冻结
					model.addAttribute( "error",  "用户状态为冻结"); 
				}else{
					model.addAttribute( "error",  "该用户不存在");
				}
			}else{
				model.addAttribute( "error",  "密码错误"); //密码错误
				log.info( "login error : passwordError");
			}
		}else{
			model.addAttribute( "error",  "该用户不存在");	//用户名不存在
			log.info( "login error : userError");
		}
		return url;
	}
	
	/**
	 * 用户注册
	 * @param user
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/register",method=RequestMethod.POST)
	public String register(@ModelAttribute UserEntity user,Model model){
		String url = "login";
		user.setRole("1");
		user.setStatus("0");
		int id = userService.addUser(user);
		if(id>0){
			model.addAttribute( "info",  "注册成功，等待管理员审核");	//注册成功
			log.info("register success ");
		}else{
			model.addAttribute( "error", "注册失败，此用户名已注册");
			model.addAttribute( "user", user);
			url = "register";
			log.info( "register error");
		}
		return url;
	}
	
	/**
	 * 管理员操作：添加新用户
	 * @param user
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/adduser",method=RequestMethod.POST)
	@ResponseBody
	public String addUser(@ModelAttribute UserEntity user,Model model){
		int id = userService.addUser(user);
		JSONObject result = new JSONObject();
		
		if(id>0){
			result.put( "success",  "add user success !!!");
		}else{
			result.put( "errorMsg",  "add user failed !!!");
		}
		return result.toString();
	}
	
	/**
	 * 管理员操作：删除用户
	 * @param user
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/deleteuser",method=RequestMethod.GET)
	@ResponseBody
	public String deleteUser(@ModelAttribute UserEntity user,Model model){
		UserEntity ue = userService.getOneUser(user);
		ue.setStatus( "-1");
		int id = userService.updateUser(ue);
		
		JSONObject result = new JSONObject();
		
		if(id>0){
			result.put( "success",  "delete user success !!!");
		}else{
			result.put( "errorMsg",  "delete user failed !!!");
		}
		return result.toString();
	}
	/**
	 * 管理员操作：更新用户信息
	 * @param user
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/updateuser",method=RequestMethod.POST)
	@ResponseBody
	public String updateUser(@ModelAttribute UserEntity user,Model model){
		
		int id = userService.updateUser(user);
		
		JSONObject result = new JSONObject();
		
		if(id>0){
			result.put( "success",  "update user success !!!");
		}else{
			result.put( "errorMsg",  "update user failed !!!");
		}
		return result.toString();
	}
	
	/**
	 * 管理员操作：获取用户列表
	 * @param user
	 * @param page
	 * @param rows
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/getuserlist",method=RequestMethod.POST)
	@ResponseBody
	public String getUserList(@ModelAttribute UserEntity user,
			@RequestParam(value="page",defaultValue="0") int page,
			@RequestParam(value="rows",defaultValue="10") int rows,
			Model model){
		int offset = (page-1)*rows;
		int total = userService.getCount(user, page, rows);
		List<UserEntity> userList = userService.getAllUserList(user, offset, rows); 
		
		JSONArray arr = new JSONArray(userList);
		JSONObject data = new JSONObject();
		data.put( "total", total);
		data.put( "rows", arr);
		
		return data.toString();
	}
	
}
